using UserApi.Common;
using UserApi.Data;
using UserApi.Dtos;
using UserApi.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;

namespace UserApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private ApiDbContext _db;
    public UserController(ApiDbContext db)
    {
        _db = db;
    }

    [HttpGet]
    public IActionResult GetAllUsers()
    {
        var users = _db.User.ToList();
        if (users.Count != 0)
        {
            System.Console.WriteLine(users.Count);
            return Ok(ApiResponse<List<User>>.Success(users));
        }
        else
        {
            return NotFound(ApiResponse<string>.Fail(501, "暂无用户"));
        }

    }

    [HttpPost]
    public IActionResult AddUser(UserDto userDto)
    {
        var user = new User { UserName = userDto.UserName, Age = userDto.Age };
        var obj = _db.User.Add(user).Entity;
        _db.SaveChanges();
        return Ok(ApiResponse<User>.Success(obj, "新增成功"));
    }

    [HttpPut("{id}")]
    public IActionResult EditUser(Guid id, UserDto userDto)
    {
        var user = _db.User.FirstOrDefault(x => x.Id == id);
        if (user != null)
        {
            user.UserName = userDto.UserName;
            user.Age = userDto.Age;
            user.UpdatedAt = DateTime.UtcNow;

            //将修改用户的人的id传给修改者字段,实际操作中应使用登录者的id
            user.UpdatedBy = user.Id;

            _db.User.Update(user);
            _db.SaveChanges();
            return Ok(ApiResponse<UserDto>.Success(userDto, "修改成功"));
        }
        else
        {
            return NotFound(ApiResponse<string>.Fail(501, "查无此人,修改失败"));
        }
    }

    [HttpDelete("{id}")]
    public IActionResult DelUser(Guid id)
    {
        var user = _db.User.FirstOrDefault(x => x.Id == id);
        if (user != null)
        {
            _db.User.Remove(user);
            _db.SaveChanges();
            return Ok(ApiResponse<User>.Success(user, "删除成功"));
        }
        else
        {
            return NotFound(ApiResponse<string>.Fail(501, "查无此人,删除失败"));
        }
    }
}